package com.catfairy.gateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author 猫大仙
 */
@Slf4j
@Component
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomConfig> implements Ordered {
  public CustomGatewayFilterFactory() {
   super(CustomConfig.class);
  }

  @Override
  public GatewayFilter apply(CustomConfig config) {
   return new GatewayFilter() {
    /**
     * ServerWebExchange: http请求-响应交互,提供对http请求和响应的访问
     * GatewayFilterChain: 过滤器链
     * Mono: reactor核心类,数据流发布者,最多只能触发一个事件
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
     //pre类型,执行请求,post类型
     log.info("Pre Filter config:{}", config);
     return chain.filter(exchange).then(Mono.fromRunnable(() -> {
      log.info("Post Filter......");
     }));
    }
   };
  }

  @Override
  public int getOrder() {
   return Ordered.LOWEST_PRECEDENCE;
  }
}
